package org.bizon.dinner.gui.topcompoments;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import org.bizon.dinner.gui.dialogs.SecuritySystem;

import diiner.common.webaccess.MenuItem;
import diiner.common.webaccess.UnAutorizationException_Exception;

public class AdminTableModel extends AbstractTableModel {

	private static final long serialVersionUID = -3372723778271481912L;
	List<MenuItem> items;

	private static String columns[] = new String[] { "name", "price", "avability" };

	public AdminTableModel() {
		super();
		try {
			items = SecuritySystem.getDinnerService().getMenuList(SecuritySystem.getID());
			fireTableDataChanged();
		} catch (UnAutorizationException_Exception e) {
			SecuritySystem.showError(e);
			items = new ArrayList<MenuItem>();
		}
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return columnIndex == 2 ? Boolean.class : String.class;
	}

	@Override
	public int getColumnCount() {
		return 3;
	}

	@Override
	public String getColumnName(int column) {
		return columns[column];
	}

	@Override
	public int getRowCount() {
		return items == null ? 0 : items.size();
	}

	@Override
	public Object getValueAt(int row, int column) {
		switch (column) {
		case 0:
			return items.get(row).getName();
		case 1:
			return items.get(row).getPrice();
		case 2:
			return Boolean.valueOf(items.get(row).isEnabled());
		}
		return null;
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return true;
	}

	@Override
	public void setValueAt(Object aValue, int row, int column) {
		switch (column) {
		case 0:
			items.get(row).setName(aValue.toString());
		case 1: {
			try {
				items.get(row).setPrice(Double.valueOf(aValue.toString()));
			} catch (NumberFormatException e) {
			}
		}
		case 2:
			items.get(row).setEnabled((Boolean.parseBoolean(aValue.toString())));
		}
		fireTableDataChanged();
		// super.setValueAt(aValue, row, column);
	}

	public void addItem(String name, String price) {
		MenuItem item = new MenuItem();
		item.setName(name);
		item.setPrice(Double.parseDouble(price));
		item.setEnabled(true);
		items.add(item);
		fireTableDataChanged();
	}
}
